package com.tuanzi.loan.business.service.xhh.settlementsystem.impl;

import com.tuanzi.loan.business.entity.family.ProductInfo;
import com.tuanzi.loan.business.entity.xhh.settlementsystem.XhhSettlementCompany;
import com.tuanzi.loan.business.entity.xhh.settlementsystem.XhhSettlementIncome;
import com.tuanzi.loan.business.entity.xhh.settlementsystem.XhhSettlementIncomeActivity;
import com.tuanzi.loan.business.repository.xhh.settlementsystem.XhhSettlementCompanyRepository;
import com.tuanzi.loan.business.repository.xhh.settlementsystem.XhhSettlementIncomeActivityRepository;
import com.tuanzi.loan.business.repository.xhh.settlementsystem.XhhSettlementIncomeRepository;
import com.tuanzi.loan.business.service.xhh.settlementsystem.XhhBillStatus;
import com.tuanzi.loan.business.service.xhh.settlementsystem.XhhSettlementIncomeService;
import com.tuanzi.loan.core.aspect.Debug;
import com.tuanzi.loan.core.repository.JPAAuditRepository;
import com.tuanzi.loan.core.service.BaseAuditServiceImpl;
import com.tuanzi.loan.core.vo.PageSearcher;
import com.tuanzi.loan.vo.request.xhh.settlementsystem.XhhSettlementIncomeRequest;
import com.tuanzi.loan.vo.response.xhh.settlementsystem.XhhSettlementIncomeResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.retry.RetryException;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author caiwanlin
 * @create 2018-08-20 14:02
 */
@Debug
@Slf4j
@Service
@Transactional
@Retryable(value = { RetryException.class })
public class XhhSettlementIncomeServiceImpl extends BaseAuditServiceImpl<XhhSettlementIncome, Long> implements XhhSettlementIncomeService {

	@Autowired
	private XhhSettlementIncomeRepository xhhSettlementIncomeRepository;
	@Autowired
	private XhhSettlementIncomeActivityRepository xhhSettlementIncomeActivityRepository;
	@Autowired
	private XhhSettlementCompanyRepository xhhSettlementCompanyRepository;

	@Override
	public Page<XhhSettlementIncomeResponse> list(PageSearcher<XhhSettlementIncomeRequest> pageSearcher) {
		return xhhSettlementIncomeRepository.list(pageSearcher.getSearchCondition(), pageSearcher.getPageable());
	}

	@Override
	public void onSave(XhhSettlementIncome settlementIncome, List<ProductInfo> activityList, List<Long> selectActivityIdList, Boolean isSpecialChannel) {
		Long settlementIncomeId = settlementIncome.getId();
		List<XhhSettlementIncomeActivity> collect = activityList.parallelStream().filter(a -> {
			return selectActivityIdList.contains(a.getId().toString());

		}).map(a -> {
			XhhSettlementIncomeActivity incomeActivity = null;
			if (settlementIncomeId != null) {
				incomeActivity = xhhSettlementIncomeActivityRepository.findSettlementIncomeActivityByActivityIdAndIncomeId(a.getId(), settlementIncomeId);
			}
			if (incomeActivity == null)
				incomeActivity = new XhhSettlementIncomeActivity();
			incomeActivity.setActivityId(a.getId());
			incomeActivity.setActivityName(a.getName());
			return incomeActivity;
		}).collect(Collectors.toList());

		// 如果是添加，未开票状态
		if (settlementIncomeId == null)
			settlementIncome.setBillStatus(XhhBillStatus.NO_BILL.index);

		// 查询uv
		// 计算除公众号推广渠道外的UV价值
		if (!isSpecialChannel) {
			Integer uv = xhhSettlementIncomeActivityRepository.getUv(settlementIncome.getStartTime(), settlementIncome.getEndTime(), selectActivityIdList);
			if (uv <= 0) {
				settlementIncome.setParticipateUv(0);
				settlementIncome.setUvValue(0.0);
			} else {
				settlementIncome.setParticipateUv(uv);
				settlementIncome.setUvValue(settlementIncome.getIncomeAmount() / uv);
			}
		}

		// 更新主体的消耗金额
		// Double incomeAmount = null;
		// Double expendAmount = null;
		// SettlementCompany company = null;
		// Double lastIncomeAmount = settlementIncome.getLastIncomeAmount();//最后一次消耗金额
		// try {
		// lock.lock();
		// company =
		// settlementCompanyRepository.findOne(settlementIncome.getCompanyId());
		// expendAmount = company.getExpendAmount();
		// incomeAmount = settlementIncome.getIncomeAmount();
		// log.warn("updateCompanyExpend companyExpendAmount:{}, incomeAmount:{}",
		// expendAmount, incomeAmount);
		// if (expendAmount == null || Double.compare(0.0, expendAmount) == 0) {
		// company.setExpendAmount(incomeAmount);
		// } else {
		// if (settlementIncomeId == null) { //如果是添加消耗记录，公司的消耗金额 = 原始消耗金额 + 结算金额
		// company.setExpendAmount(expendAmount + incomeAmount);
		// log.warn("newIncome companyExpendAmount:{}", company.getExpendAmount());
		// } else { //如果是修改消耗记录，公司的消耗金额 = 原始消耗金额 - 最后一次结算金额 + 要更新的结算金额
		// if (!lastIncomeAmount.equals(incomeAmount)) { //上次消耗金额和这次消耗金额不同才更新
		// company.setExpendAmount(expendAmount - lastIncomeAmount + incomeAmount);
		// log.warn("modifiedIncome companyExpendAmount:{}", company.getExpendAmount());
		// }
		// }
		// }
		// settlementCompanyRepository.save(company);
		// } catch (Exception e) {
		// log.error(e.getMessage(), e);
		// } finally {
		// lock.unlock();
		// }

		// 保存消耗记录
		settlementIncome.setLastIncomeAmount(settlementIncome.getIncomeAmount());
		xhhSettlementIncomeRepository.save(settlementIncome);

		// 保存关联活动
		if (CollectionUtils.isNotEmpty(collect)) {
			collect.forEach(s -> s.setIncomeId(settlementIncome.getId()));
			xhhSettlementIncomeActivityRepository.save(collect);
		}
		// 插入余额记录
		/*
		 * SettlementRemain settlementRemain = null; if (settlementIncomeId == null){
		 * //添加消耗记录情况 settlementRemain = new SettlementRemain();
		 * settlementRemain.setCompanyId(company.getId());
		 * settlementRemain.setCompanyName(company.getCompanyName());
		 * settlementRemain.setRemainType(RemainType.EXPEND.index);
		 * settlementRemain.setRelateId(settlementIncome.getId());
		 * settlementRemain.setPrePrepayAmount(company.getPrepayAmount());
		 * settlementRemain.setPrepayAmount(company.getPrepayAmount());
		 * settlementRemain.setPreExpendAmount(expendAmount == null?0:expendAmount);
		 * settlementRemain.setExpendAmount(company.getExpendAmount());
		 * settlementRemain.setPreRemainAmount(settlementRemain.getPrePrepayAmount()-
		 * settlementRemain.getPreExpendAmount());
		 * settlementRemain.setRemainAmount(settlementRemain.getPrepayAmount()-
		 * settlementRemain.getExpendAmount());
		 * settlementRemainRepository.save(settlementRemain); } else {//更改消耗记录情况 if
		 * (lastIncomeAmount == incomeAmount) return;//上次消耗金额和这次消耗金额不同才会执行更新操作
		 * settlementRemain = settlementRemainRepository
		 * .findSettlementRemainByRelateIdAndRemainType(settlementIncomeId,RemainType.
		 * EXPEND.index); Double oldPreExpendAmount =
		 * settlementRemain.getPreExpendAmount(); Double oldExpendAmount =
		 * settlementRemain.getExpendAmount(); //更新消耗金额 //
		 * settlementRemain.setPreExpendAmount(oldPreExpendAmount - lastIncomeAmount);
		 * settlementRemain.setExpendAmount(oldExpendAmount - lastIncomeAmount +
		 * incomeAmount); //更新余额
		 * settlementRemain.setPreRemainAmount(settlementRemain.getPrePrepayAmount()-
		 * settlementRemain.getPreExpendAmount());
		 * settlementRemain.setRemainAmount(settlementRemain.getPrepayAmount() -
		 * settlementRemain.getExpendAmount());
		 * settlementRemainRepository.save(settlementRemain); }
		 */
	}

	@Override
	public List<XhhSettlementIncome> findAllByBillId(Long billId) {
		return xhhSettlementIncomeRepository.findAllByBillId(billId);
	}

	@Override
	public void updateCompanyNameByCompanyId(Long companyId, String companyName) {
		xhhSettlementIncomeRepository.updateCompanyNameByCompanyId(companyId, companyName);
	}

	@Override
	public void updateProductNameByProductId(Long productId, String productName) {
		xhhSettlementIncomeRepository.updateProductNameByProductId(productId, productName);
	}

	@Override
	public void updateCompanyIdAndCompanyNameByCompanyId(Long companyId, String companyName, Long newCompanyId) {
		xhhSettlementIncomeRepository.updateCompanyIdAndCompanyNameByCompanyId(companyId, companyName, newCompanyId);
	}

	@Override
	public void deleteByCompanyId(Long companyId) {
		xhhSettlementIncomeRepository.deleteByCompanyId(companyId);
	}

	@Override
	public void deleteByProductId(Long productId) {
		xhhSettlementIncomeRepository.deleteByProductId(productId);
	}

	@Override
	public void onDelete(Long id) {
		XhhSettlementIncome income = xhhSettlementIncomeRepository.findOne(id);
		if (null == income) {
			return;
		}

		XhhSettlementCompany company = xhhSettlementCompanyRepository.findOne(income.getCompanyId());
		if (null == company) {
			return;
		}

		Double expendAmount = company.getExpendAmount();
		Double incomeAmount = income.getIncomeAmount();
		company.setExpendAmount(expendAmount - incomeAmount);
		xhhSettlementCompanyRepository.save(company);

		xhhSettlementIncomeRepository.delete(income);
	}

	@Override
	public List<XhhSettlementIncome> findAllByProductId(Long productId) {
		return xhhSettlementIncomeRepository.findAllByProductId(productId);
	}

	@Override
	public Double sumRangeTotalAmount(XhhSettlementIncomeRequest request) {
		return xhhSettlementIncomeRepository.sumRangeTotalAmount(request);
	}

	@Override
	public Double sumRangeTotalUvValue(XhhSettlementIncomeRequest request) {
		return xhhSettlementIncomeRepository.sumRangeTotalUvValue(request);
	}

	@Override
	protected JPAAuditRepository<XhhSettlementIncome, Long> getRepository() {
		return xhhSettlementIncomeRepository;
	}
}
